import React from 'react';
import {
	DndContext,
	closestCenter,
	KeyboardSensor,
	PointerSensor,
	useSensor,
	useSensors,
	type DragEndEvent
} from '@dnd-kit/core';
import {
	arrayMove,
	SortableContext,
	sortableKeyboardCoordinates,
	rectSortingStrategy
} from '@dnd-kit/sortable';
import { GridContentStyle } from './style';
import SortableItem from './SortableItem';
import type { MainComProps } from './type';

const GridList = (<T extends { id: number; [key: string]: any }>(props: MainComProps<T>) => {
	const { dragSort, data, component, setData } = props;

	const sensors = useSensors(
		useSensor(PointerSensor),
		useSensor(KeyboardSensor, {
			coordinateGetter: sortableKeyboardCoordinates
		})
	);

	const handleDragEnd = (event: DragEndEvent) => {
		const { active, over } = event;
		if (active.id !== over.id) {
			const oldIndex = data.findIndex((item) => item.id === active.id);
			const newIndex = data.findIndex((item) => item.id === over.id);
			const newArr = arrayMove(data, oldIndex, newIndex);
			setData(newArr);
		}
	};

	return (
		<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
			<SortableContext items={data} strategy={rectSortingStrategy}>
				<GridContentStyle>
					{data.map((item) =>
						item.id ? (
							<SortableItem key={item.id} id={item.id} disabled={!dragSort}>
								{component(item)}
							</SortableItem>
						) : (
							'缺少id'
						)
					)}
				</GridContentStyle>
			</SortableContext>
		</DndContext>
	);
}) as <T extends { id: number; [key: string]: any }>(props: MainComProps<T>) => React.ReactElement;

export default GridList;
